import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory, Reflector } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { ApiKeyGuard } from './common/guards/api-key.guard';
import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor';
import { WrapResponseInterceptor } from './common/interceptors/wrap-response.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(
    new ValidationPipe({
      /**
       * 启用白名单功能
       * 比如创建一个数据，当用户传入无关的属性时，即于dto无关的属性
       * 将会自动玻璃或者删除
       */
      whitelist: true,
      forbidNonWhitelisted: true,
      // 将请求 body 的参数进行转化，转化成我们所需的dto类型
      // 将请求 param 参数 id转化为我们所需的number类型
      transform: true,

      transformOptions: {
        // 自动转换，我们在dto中，可以注释掉@type的装饰，不用指明转换为某个类型，比如number
        enableImplicitConversion: true,
      },
    }),
  );

  app.useGlobalFilters(new HttpExceptionFilter());

  // app.useGlobalGuards(new ApiKeyGuard(new Reflector(), new ConfigService()));

  app.useGlobalInterceptors(
    new WrapResponseInterceptor(),
    new TimeoutInterceptor(),
  );

  const options = new DocumentBuilder()
    .setTitle('bozai Coffee')
    .setDescription('coffee aplication')
    .setVersion('0.0.1')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document);

  await app.listen(3000);
}
bootstrap();

